package com.ley.yikang.controller;

import com.ley.yikang.Annotation.PassToken;
import com.ley.yikang.Annotation.UserLoginToken;
import com.ley.yikang.entity.*;
import com.ley.yikang.service.*;
import com.ley.yikang.util.ResultData;
import com.ley.yikang.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin
@RequestMapping("/elder")
public class ElderController {
    private final ElderService elderService;
    private final DoctorService doctorService;
    private final ChildService childService;
    private final CheckTaskService checkTaskService;
    private final HealthInfoService healthInfoService;

    private final ElderAndChildBindService elderAndChildBindService;

    @Autowired
    public ElderController(ElderService elderService, DoctorService doctorService, ChildService childService, CheckTaskService checkTaskService, HealthInfoService healthInfoService, ElderAndChildBindService elderAndChildBindService) {
        this.elderService = elderService;
        this.doctorService = doctorService;
        this.childService = childService;
        this.checkTaskService = checkTaskService;
        this.healthInfoService = healthInfoService;
        this.elderAndChildBindService = elderAndChildBindService;
    }

    @PassToken
    @PostMapping("/register")
    public ResultData<Boolean> addUser(@RequestBody Elder elder) {
        //判断手机号是否合法
        if (!elder.getPhone().matches("1(3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}")) {
            System.out.println("手机号不合法！");
            return ResultData.fail("手机号不合法！");
        }
        //System.out.println(!elder.getPhone().matches("1(3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}"));
        //判断用户是否存在
        Elder elder1 = elderService.findElder(elder.getPhone());
        if (elder1 == null) {
            elderService.addElder(elder);
            Elder elder2 = elderService.findElder(elder.getPhone());
            healthInfoService.addHealthInfo(new HealthInfo(0, elder2.getId(), null, null));
            System.out.println("注册老人用户成功！");
            return ResultData.success(true, "用户注册成功！");
        } else {
            System.out.println("注册老人用户失败,该手机号已被使用！");
            return ResultData.fail("用户注册失败,该手机号已被使用！");
        }
    }

    @PassToken
    @PostMapping(value = "/login")
    public ResultData<String> login(@RequestBody Elder elder) {
        Elder elder1 = elderService.findElder(elder.getPhone());
        if (elder1 != null) {
            //系统中有这样的用户
            if (elder1.getPassword().equals(elder.getPassword())) {
                System.out.println("找到老人用户！登陆成功！");
                //返回token
                return ResultData.success(TokenUtil.getElderToken(elder1), "用户登陆成功！");
            } else {
                System.out.println("密码错误！登陆失败！");
                return ResultData.fail("密码错误！登陆失败！");
            }
        } else
            return ResultData.fail("用户名或密码错误！");
    }

    @UserLoginToken
    @DeleteMapping("/delElder")
    public ResultData<Boolean> delete(@RequestBody Elder elder) {
        //判断老人用户是否存在
        if (elderService.findElderById(elder.getId()) == null) {
            System.out.println("没有找到该老人用户！删除失败！");
            return ResultData.fail("没有找到该老人用户！删除失败！");
        }
        //先删除老人绑定子女信息
        elderAndChildBindService.delElderAndChild(elder.getId());
        //删除老人检查任务信息
        checkTaskService.delElderCheckTask(elder.getId());
        //删除老人健康信息
        healthInfoService.delHealthInfo(elder.getId());
        //删除老人信息
        elderService.delElder(elder.getId());
        System.out.println("删除老人用户：" + elder.getId());
        return ResultData.success(true, "用户删除成功！");
    }

    @UserLoginToken
    @PostMapping("/updateElder")
    public ResultData<Elder> update(@RequestBody Elder elder) {
        //判断用户是否存在
        if (elderService.findElderById(elder.getId()) == null) {
            System.out.println("没有找到老人用户！修改失败！");
            return ResultData.fail("没有找到该老人用户！修改失败！");
        }
        //判断是否有使用该手机号的用户
        if (elderService.findElder(elder.getPhone()) != null && elderService.findElder(elder.getPhone()).getId() != elder.getId()) {
            System.out.println("手机号已被使用！修改失败！");
            return ResultData.fail("手机号已被使用！修改失败！");
        }
        elderService.updateElder(elder);
        System.out.println("修改老人用户：" + elder.getPhone());
        return ResultData.success(elder, "用户修改成功！");
    }

    @UserLoginToken
    @GetMapping("/findAll")
    public ResultData<List<Elder>> findAll(
            @RequestParam(required = false) String elderName,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) Integer communityId
    ) {
        List<Elder> elders = elderService.findAll(elderName, phone, communityId);
        System.out.println("查询老人用户");
        return ResultData.success(elders, "用户查询成功！");
    }

    @UserLoginToken
    @GetMapping("/findElderById")
    public ResultData<Elder> findElderById(int elderId) {
        Elder elder = elderService.findElderById(elderId);
        if (elder == null) {
            System.out.println("没有找到该老人用户！");
            return ResultData.fail("没有找到该老人用户！");
        }
        System.out.println("用户信息查询成功！");
        return ResultData.success(elder, "用户信息查询成功！");
    }

    @UserLoginToken
    @GetMapping("/findElderByPhone")
    public ResultData<Elder> findElderByPhone(String phone) {
        Elder elder = elderService.findElder(phone);
        if (elder == null) {
            System.out.println("没有找到该老人用户！");
            return ResultData.fail("没有找到该老人用户！");
        }
        System.out.println("用户信息查询成功！");
        return ResultData.success(elder, "用户信息查询成功！");
    }

    @UserLoginToken
    @GetMapping("/findElderByToken")
    public ResultData<Elder> findElderByToken(String token) {
        int id = TokenUtil.getTokenUserId(token);
        Elder elder = elderService.findElderById(id);
        if (elder == null) {
            System.out.println("没有找到该老人用户！");
            return ResultData.fail("没有找到该老人用户！");
        }
        System.out.println("用户信息查询成功！");
        return ResultData.success(elder, "用户信息查询成功！");
    }

    @UserLoginToken
    @PostMapping("/addCheckTask")
    public ResultData<Boolean> addCheckTask(@RequestBody CheckTask checkTask) {
        Elder elder = elderService.findElderById(checkTask.getElderId());
        //老人用户是否存在
        if (elder == null) {
            System.out.println("没有找到老人用户！添加失败！");
            return ResultData.fail("没有找到该老人用户！添加失败！");
        }
        //判断子女是否存在(childId=0为特殊存在)
        if (checkTask.getElderId() != 0) {
            if (childService.findChildById(checkTask.getChildId()) == null) {
                System.out.println("没有找到子女用户！添加失败！");
                return ResultData.fail("没有找到该子女用户！添加失败！");
            }
        }
        //判断当天是否已经预约
        List<CheckTask> checkTask1 = checkTaskService.getElderCheckTask(checkTask.getElderId(), checkTask.getDate());
        if (!checkTask1.isEmpty()) {
            System.out.println("不可以添加");
            return ResultData.fail("您今日预约健康检测任务以达到上限，明天再来试试吧！");
        } else {
            //获取所有检测任务
            List<CheckTask> list = checkTaskService.getAllCheckTask();
            //筛选出当前传入接口日期的那一天的检测任务
            list = list.stream().filter(item -> item.getDate().getTime() == checkTask.getDate().getTime()).toList();
            //判断list的数量是否为社区医生数量的10倍
            if (list.size() >= doctorService.findAll(null, null, elder.getCommunityId()).size() * 10) {
                System.out.println("不可以添加");
                return ResultData.fail("今日您所在的社区预约健康检测任务以达到上限，明天再来试试吧！");
            }
            System.out.println("可以添加");
            //如果checkTask里面医生id为0则随机选择一个医生
            if (checkTask.getDoctorId() == 0) {
                //添加医生id
                List<Doctor> list1 = doctorService.findAll(null, null, elder.getCommunityId());
                //选择有检测任务最少的一个医生
                Doctor doctor1 = list1.stream().min(Comparator.comparingInt(item -> checkTaskService.getDoctorCheckTask(item.getId(), null, 0).size())).get();
                checkTask.setDoctorId(doctor1.getId());
            }
            Doctor doctor = doctorService.findDoctorById(checkTask.getDoctorId());
            //判断医生和老人是否在同一个社区
            if (doctor.getCommunityId() != elder.getCommunityId()) {
                System.out.println("老人和医生不在同一个社区！添加失败！");
                return ResultData.fail("老人和医生不在同一个社区！添加失败！");
            }
            //设置完成和是否有问题
            checkTask.setFinish(false);
            checkTask.setHasQuestion(false);
            //添加检测任务到数据库
            checkTaskService.addCheckTask(checkTask);
            System.out.println("添加检测任务成功！");
            return ResultData.success(true, "添加检测任务成功！");
        }
    }

    @UserLoginToken
    @GetMapping("/getElderCheckTask")
    public ResultData<List<CheckTask>> getElderCheckTask(@RequestParam int elderId, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        //判断老人用户是否存在
        if (elderService.findElderById(elderId) == null) {
            System.out.println("没有找到老人用户！查询失败！");
            return ResultData.fail("没有找到该老人用户！查询失败！");
        }
        List<CheckTask> checkTask = checkTaskService.getElderCheckTask(elderId, date);
        //把checkTask按日期倒着排序
        checkTask.sort((o1, o2) -> o2.getDate().compareTo(o1.getDate()));
        System.out.println("查询老人检测任务");
        return ResultData.success(checkTask, "查询老人检测任务成功！");
    }

    @UserLoginToken
    @DeleteMapping("/delElderCheckTask")
    public ResultData<Boolean> delElderCheckTask(int id) {
        //判断id是否存在
        if (checkTaskService.getCheckTaskById(id) == null) {
            System.out.println("没有找到该检查任务！删除失败！");
            return ResultData.fail("没有找到该检查任务！删除失败！");
        }
        checkTaskService.delCheckTask(id);
        System.out.println("删除老人检测任务");
        return ResultData.success(true, "删除老人检测任务成功！");
    }

    @UserLoginToken
    @PostMapping("/updateElderCheckTask")
    public ResultData<Boolean> updateElderCheckTask(@RequestBody CheckTask checkTask) {
        if (checkTaskService.getCheckTaskById(checkTask.getId()) == null) {
            System.out.println("没有找到医生检查任务！修改失败！");
            return ResultData.fail("没有找到该检查任务！修改失败！");
        }
        //判断医生和老人是否在同一个社区
        Doctor doctor = doctorService.findDoctorById(checkTask.getDoctorId());
        Elder elder = elderService.findElderById(checkTask.getElderId());
        if (doctor.getCommunityId() != elder.getCommunityId()) {
            System.out.println("老人和医生不在同一个社区！修改失败！");
            return ResultData.fail("老人和医生不在同一个社区！修改失败！");
        }
        //判断是否完成的状态和是否有问题是否冲突
        if (!checkTask.isFinish() && checkTask.isHasQuestion()) {
            System.out.println("完成状态和是否有问题冲突！修改失败！");
            return ResultData.fail("完成状态和是否有问题冲突！修改失败！");
        }
        //判断checkTask中当天是否已经有了检测任务
        List<CheckTask> checkTask1 = checkTaskService.getElderCheckTask(checkTask.getElderId(), checkTask.getDate());
        if (!checkTask1.isEmpty() && checkTask.getId() != checkTask1.get(0).getId()) {
            System.out.println("不可以修改");
            return ResultData.fail("您今日预约健康检测任务以达到上限，明天再来试试吧！");
        }
        //获取所有检测任务
        List<CheckTask> list = checkTaskService.getAllCheckTask();
        //筛选出当前传入接口日期的那一天的检测任务
        list = list.stream().filter(item -> item.getDate().getTime() == checkTask.getDate().getTime()).toList();
        //判断list的数量是否为社区医生数量的10倍
        if (list.size() >= doctorService.findAll(null, null, elder.getCommunityId()).size() * 10) {
            System.out.println("不可以修改");
            return ResultData.fail("今日您所在的社区预约健康检测任务以达到上限，明天再来试试吧！");
        }

        checkTaskService.updateElderCheckTask(checkTask);
        System.out.println("修改老人检测任务");
        return ResultData.success(true, "修改老人检测任务成功！");
    }

    @UserLoginToken
    @GetMapping("/getHealthInfo")
    public ResultData<HealthInfo> getHealthInfo(int elderId) {
        //判断id是否存在
        if (elderService.findElderById(elderId) == null) {
            System.out.println("该老人用户不存在！");
            return ResultData.fail("该用户不存在！");
        }
        System.out.println("查询老人健康信息");
        return ResultData.success(healthInfoService.getHealthInfo(elderId), "查询老人健康信息成功！");
    }

    @UserLoginToken
    @PostMapping("/updateHealthInfo")
    public ResultData<Boolean> updateHealthInfo(@RequestBody HealthInfo healthInfo) {
        //判断id是否存在
        if (elderService.findElderById(healthInfo.getElderId()) == null) {
            System.out.println("该老人用户不存在！");
            return ResultData.fail("该用户不存在！");
        }
        //如果healthInfo.getMedical_history() == ""或healthInfo.getMedication_records() == ""，那么把他们都设置为null
        if (Objects.equals(healthInfo.getMedical_history(), "")) {
            healthInfo.setMedical_history(null);
        }
        if (Objects.equals(healthInfo.getMedication_records(), "")) {
            healthInfo.setMedication_records(null);
        }
        healthInfoService.updateHealthInfo(healthInfo);
        System.out.println("修改老人健康信息");
        return ResultData.success(true, "修改老人健康信息成功！");
    }

    @UserLoginToken
    @GetMapping("/getElderAndChild")
    public ResultData<List<Child>> getElderAndChild(int elderId) {
        System.out.println("查询老人和儿童关系");
        return ResultData.success(elderAndChildBindService.getElderAndChild(elderId), "查询成功！");
    }
}
